//
//  HomeListController.m
//  QQplayground
//
//  Created by zhangxy on 2018/6/8.
//  Copyright © 2018年 zhang. All rights reserved.
//

#import "HomeListController.h"
#import "ZZHomeListCell.h"
#define cellIdentifier @"ZZHomeListCell"
#import <SDCycleScrollView/SDCycleScrollView.h>
#import "ZZHomeLabelView.h"
#import "ZZContentDetailController.h"
#import "ZZShareView.h"
#import "ZZContentCommentController.h"
#import "MyButton.h"
#import <MJRefresh.h>

@interface HomeListController ()<SDCycleScrollViewDelegate,UITableViewDelegate,UITableViewDataSource,ZZTopicCellDelegate>{
    int page;
    MyButton *checkMenuBtn;
    NavTypeEntity *checkLabel;
}

@property(nonatomic,strong)  NSMutableArray *listArray;
@property(nonatomic,strong)  NSArray *headerArr;
@property(nonatomic,strong)  UITableView *listTable;
@property(nonatomic,strong)  ZZHomeLabelView *labelView;


@end

@implementation HomeListController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view
    
    [self createTableView];
    
}

-(void)createTableView{
    _listArray = [[NSMutableArray alloc] init];
    
    _listTable=[self.view createTableView:self cell:cellIdentifier];
    [_listTable setFrame:self.view.bounds];
    
    [_listTable setBackgroundColor:UIColorFromRGB(BgSystemColor)];
    
    if (iOS7) {
        _listTable.backgroundView = nil;
    }
    
    [_listTable setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    
    MJRefreshBackFooter *footer = [MJRefreshBackFooter  footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    
    _listTable.footer = footer;
    [self setTableSeparatorInset];
    
    
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    
    _labelView = [[ZZHomeLabelView alloc] initWithTable:_listTable result:^(id tag, NSString *title) {
        checkLabel = tag;
        
        [self loadBegin];
    }];
    _labelView.superVC = self;
    _listTable.tableHeaderView = _labelView;
    
    
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self loadBegin];
    }];
    header.stateLabel.hidden=YES;
    header.lastUpdatedTimeLabel.hidden=YES;
    _listTable.header = header;
}

-(void)onItemClick:(MyButton *)btn{
    if(checkMenuBtn.tag == btn.tag){
        return;
    }
    checkMenuBtn.selected = NO;
    
    btn.selected = YES;
    checkMenuBtn = btn;
    
    
    [self loadBegin];
}


-(void)setEntity:(NavTypeEntity *)entity{
    _entity = entity;
    
    if(_labelView){
        [_labelView setEntiy:entity];
    }
    
    [NetworkUtil POST:API_GetNavList parameters:@{@"nav_id":_entity.nav_id} success:^(id responseObject, NSDictionary *dict) {
        if([_entity.nav_name isEqual:@"推荐"]){
            UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 130)];
            [imgView setBackgroundColor:UIColorFromRGB(BgTitleColor)];
            [self.view insertSubview:imgView atIndex:0];
        }
    } failure:^(NSError *error, NSString *message) {
        
    }];
    
    [self loadBegin];
}

-(void)loadBegin{
    page = 0;
    [self loadMoreData];
}

/**
 加载更多
 */
-(void)loadMoreData{
    //    NSDictionary *p = @{@"user_id":convertIntToString((int)[UserUtil getUser].user_id),//@"2666684",
    //                        @"nav_type":convertToString(_entity.nav_type),                                    // @"all",
    //                        @"page":convertIntToString(page),
    //                        @"page_size":@"20"
    //                        };
    
    NSString *sort_type = @"day_new";
    if(checkMenuBtn){
        sort_type =((NavTypeEntity *)checkMenuBtn.objTag).nav_type;
    }
    
    NSString *cat_id = @"0";
    NSString *tag_id = @"0";
    if(checkLabel){
        if(convertToString(checkLabel.cat_id).length > 0){
            cat_id = checkLabel.cat_id;
        }
        if(convertToString(checkLabel.tag_id).length > 0){
            tag_id = checkLabel.tag_id;
        }
    }
    NSDictionary *p = @{@"sort_type":sort_type,
                        @"cat_id":cat_id,
                        @"tag_id":tag_id,
                        @"have_comment":@"1",
                        @"page":convertIntToString(page)
                        };
    NSString *api = API_GetHomeList(_entity.nav_type);
    if([_entity.nav_type isEqual:@"gz"]){
        api = API_GetHomeFollowcontentlist;
        p = @{@"have_comment":@"1",
              @"session_uid":convertToString([UserUtil getUser].user_id),
              @"page":convertIntToString(page)};
    }else if([_entity.nav_type isEqual:@"tj"]){
        api = API_GetHomeFollowcontentlist;
        p = @{@"have_comment":@"1",
              @"session_uid":convertToString([UserUtil getUser].user_id),
              @"page":convertIntToString(page)};
    }
    [NetworkUtil POST:api parameters:p success:^(id responseObject, NSDictionary *dictionary) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        if([self.listTable.header isRefreshing]){
            [self.listTable.header endRefreshing];
        }
        if([self.listTable.footer isRefreshing]){
            [self.listTable.footer endRefreshing];
        }
        if(page == 0){
            [self.listArray removeAllObjects];
        }
        NSArray *arr = dictionary[@"data"][@"list"];
        for(NSDictionary *item in arr){
            if([item isKindOfClass:[NSDictionary class]]){
                
                ZZHomeTopicEntity *model = [[ZZHomeTopicEntity alloc] initWithDictionary:item];
                if(![_entity.nav_type isEqual:@"gz"] && ![_entity.nav_type isEqual:@"tj"]){
                    model.nav_type = _entity.nav_type;
                    model.nav_name = _entity.nav_name;
                }
                [self.listArray addObject:model];
            }
            
        }
        [self.listTable reloadData];
        if(convertToString(dictionary[@"data"][@"page"]).length>0){
            if([dictionary[@"data"][@"page"] intValue] < [dictionary[@"data"][@"pages"] intValue]){
                page = [dictionary[@"data"][@"page"] intValue] + 1;
            }
        }
        
    } failure:^(NSError *error, NSString *message) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        [PopUtil showMessage:message positionType:PopPositionTypeMiddle];
        if([self.listTable.header isRefreshing]){
            [self.listTable.header endRefreshing];
        }
        if([self.listTable.footer isRefreshing]){
            [self.listTable.footer endRefreshing];
        }
    }];
}


-(void)onCellItemClick:(ZZTopicCellClickType)type obj:(id)senderObj{
    ZZHomeTopicEntity *topic = senderObj;
    
    if(type == ZZClickShare){
        ZZShareView *shareView = [[ZZShareView alloc] initWithShareType:ZZShareTypeTopic vc:self obj:topic];
        [shareView show];
    }
    if(type == ZZClickFav || type == ZZClickStar){
        NSString *url = API_AddVote(topic.nav_type);
        NSString *typeName = @"like";
        if(type == ZZClickStar){
            typeName = @"fav";
            
            if(topic.is_fav){
                url = API_cancelvote(topic.nav_type);
            }
        }else{
            if(topic.is_like){
                url = API_cancelvote(topic.nav_type);
            }
        }
        [NetworkUtil POST:url parameters:@{@"id":convertIntToString((int)topic.t_id),
                            @"type":typeName,
                            @"session_uid":[UserUtil getUser].user_id
                            }
                  success:^(id responseObject, NSDictionary *dict) {
                      [PopUtil showMessage:dict[@"msg"]];
                      if(type==ZZClickStar){
                          topic.fav_count = dict[@"data"][@"count"];
                      }else{
                          topic.like_count = dict[@"data"][@"count"];
                      }
                      [self.listTable reloadData];
                  } failure:^(NSError *error, NSString *message) {
                      
                  }];
    }
    if(type == ZZClickComment){
        ZZContentCommentController *vc = [[ZZContentCommentController alloc] init];
        vc.entity = topic;
        [self openPushVC:vc];
    }
    if(type == ZZClickOpenVC){
        [self openPushVC:senderObj];
    }
}

#pragma mark UITableView delegate Start
// 返回section数
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

// 返回section高度
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if([_entity.nav_name isEqual:@"推荐"]){
        return 0.1f;
    }
    return 44.0f;
}

// 返回section 的View
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectZero];
    if(section == 0 && ![_entity.nav_name isEqual:@"推荐"]){
        [headerView setFrame:CGRectMake(0, 0, ScreenWidth, 44)];
        [headerView setBackgroundColor:UIColorFromRGB(BgTitleColor)];
        [self addBottomItems:headerView];
    }
    return headerView;
}


-(MyButton *) createMenuButton:(CGRect) f m:(NavTypeEntity *)entity{
    MyButton *b = [MyButton buttonWithType:UIButtonTypeCustom];
    b.titleLabel.font = FontFiftent;
    [b setTitleColor:UIColorFromRGB(TextWhiteColor) forState:UIControlStateSelected];
    [b setTitleColor:UIColorFromRGBAlpha(TextWhiteColor, 0.6) forState:UIControlStateNormal];
    [b setFrame:f];
    if(entity){
        [b setTitle:entity.cat_name forState:0];
        b.objTag = entity;
    }
    [b addTarget:self action:@selector(onItemClick:) forControlEvents:UIControlEventTouchUpInside];
    return b;
}

-(void)addBottomItems:(UIView *) sectionView{
    int i = 1;
    CGFloat sx = 15.0f;
    NSArray *types = @[@"day_new",@"day_hot",@"fav_hot",@"recomment"];
    for(NSString *item in @[@"最新",@"热门",@"推荐",@"精选"]){
        NavTypeEntity *entity = [NavTypeEntity new];
        entity.nav_id = convertIntToString(i);
        entity.nav_name = item;
        entity.nav_type = types[i-1];
        
        CGRect f = CGRectMake(22 + (i-1)*30 + (i-1)*sx, 0, 30, 44);
        MyButton *btn = [self createMenuButton:f m:entity];
        btn.tag = i;
        [btn setTitle:item forState:0];
        [btn.titleLabel setFont:FontThirteen];
        
        [sectionView addSubview:btn];
        
        if(i == 1){
            btn.selected = YES;
            checkMenuBtn = btn;
        }
        
        i = i + 1;
    }
    
    //    UIButton *btnArrow = [UIButton buttonWithType:UIButtonTypeCustom];
    //    [btnArrow setImage:[UIImage imageNamed:@"发布 素材  下拉"] forState:0];
    //    [btnArrow setFrame:CGRectMake(ScreenWidth - 44, StatusBarHeight, 44, 44)];
    //    [btnArrow addTarget:self action:@selector(arrowClick:) forControlEvents:UIControlEventTouchUpInside];
    //    [sectionView addSubview:btnArrow];
}




// 返回section下得行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _listArray.count;
}

// cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    ZZHomeListCell *cell = (ZZHomeListCell*)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil) {
        cell = [[ZZHomeListCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    }
    cell.delegate = self;
    [cell dataToView:[_listArray objectAtIndex:indexPath.row]];
    return cell;
}



// 是否显示删除功能
-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{
    return NO;
}

// 删除清理数据
-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    editingStyle = UITableViewCellEditingStyleDelete;
}


// table 行的高度
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //    return 70.0f;
    UITableViewCell *cell = [self tableView:tableView cellForRowAtIndexPath:indexPath];
    return cell.frame.size.height;
}

// table 行的点击事件
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    ZZHomeTopicEntity *model=[_listArray objectAtIndex:indexPath.row];
    ZZContentDetailController *vc = [[ZZContentDetailController alloc] init];
    vc.entity = model;
    [self openPushVC:vc];
    
    
}

//设置分割线间距
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
    if((indexPath.section+1) < _listArray.count){
        UIEdgeInsets inset = UIEdgeInsetsMake(0, 10, 0, 0);
        if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
            [cell setSeparatorInset:inset];
        }
        
        if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
            [cell setLayoutMargins:inset];
        }
    }
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    CGPoint vel = [scrollView.panGestureRecognizer velocityInView:scrollView];
    if(vel.y < 0){
        // 上拉
        if(_labelView){
            [_labelView hideTopTags];
        }
    }
}

-(void)viewDidLayoutSubviews{
    [self setTableSeparatorInset];
}
#pragma mark UITableView delegate end

/**
 *  设置UITableView分割线空隙
 */
-(void)setTableSeparatorInset{
    UIEdgeInsets inset = UIEdgeInsetsMake(0, 10, 0, 0);
    if ([_listTable respondsToSelector:@selector(setSeparatorInset:)]) {
        [_listTable setSeparatorInset:inset];
    }
    
    if ([_listTable respondsToSelector:@selector(setLayoutMargins:)]) {
        [_listTable setLayoutMargins:inset];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
